package com.zwj.spring_study.a05.postprocessor;

import com.zwj.spring_study.a05.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义后置处理器：扫描组件&&注册组件
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2024/6/9 21:30
 */
@Slf4j
public class ComponentScanPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) {
        try {
            //获取被注解@ComponentScan扫描的包的基础信息
            ComponentScan componentScan = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);
            //组件名称的生成器，可以根据 BeanDefinition 生成 beanName
            AnnotationBeanNameGenerator nameGenerator = new AnnotationBeanNameGenerator();
            if (componentScan == null) {
                return;
            }
            //遍历@componentScan的扫描路径
            for (String p : componentScan.basePackages()) {
                String path = "classpath*:" + p.replace(".", "/") + "/**/*.class";
                log.info("类路径：" + path);
                //工具类
                CachingMetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();
                //加载类路径上的资源，实际会将.class文件加载为IO输入流
                Resource[] resources = new PathMatchingResourcePatternResolver().getResources(path);
                for (Resource resource : resources) {
                    //获取一个MetaData的读取器
                    MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    ClassMetadata classMetadata = metadataReader.getClassMetadata();
                    //判断是否被@Component注解，或者派生@Component注解表示
                    if (metadataReader.getAnnotationMetadata().hasAnnotation(Component.class.getName()) ||
                            metadataReader.getAnnotationMetadata().hasMetaAnnotation(Component.class.getName())) {
                        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
                                .genericBeanDefinition(classMetadata.getClassName())
                                .getBeanDefinition();
                        //注册到容器中
                        if (configurableListableBeanFactory instanceof DefaultListableBeanFactory) {
                            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) configurableListableBeanFactory;
                            String name = nameGenerator.generateBeanName(beanDefinition, beanFactory);
                            beanFactory.registerBeanDefinition(name, beanDefinition);
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
